<?php
function generate_guestbook() {
    require(ABSPATH . 'wp-config.php');
    global $wpdb;

    $template_dir = get_template_directory();
    $template_name = get_template();
    $template_name = strtolower($template_name);
    $home_url = get_settings('home');
    $perma = get_settings('permalink_structure');

    /*
    $chmd = chmod($template_dir, 0777);

    if ($chmd) {
        $msg .= "Theme folder chmoded to 777!<br />";
    } else {
        $msg .= "Theme folder was not chmoded to 777!<br />";
    }
    */
    $source_file=dirname(__FILE__)."/livechat.php";
    $destion_file=$template_dir."/livechat.php";

    if(!copy($source_file,$destion_file))
        echo "Create File Error!!!";
    else
        echo 'Create File Successed!!!';

    //在数据库创建page_id
    $check = $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE post_status='publish' AND post_name='live-chat'");
    $content="If you change your theme , please generate template file again in your admin panel!!";
    if(!$check)
    {
        $title = "Live Chat";
        $status = "publish";
        $type = "page";

        $post_author = 1;
        $post_date = current_time('mysql');
        $post_date_gmt = current_time('mysql', 1);
        $post_content = $content;
        $post_title = $title;
        $post_status = $status;
        $post_type = $type;
        $post_data = compact('post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_title', 'post_status', 'post_type');
        $sql1 = wp_insert_post($post_data);
        //Confirm that a guestbook was indeed created:
        if ($sql1) {
            $msg .= "ChatRoom Page Created!<br />";
        } else {
            $msg .= "ChatRoom Page NOT Created!<br />";
        }

        $maxid = $wpdb->get_var("SELECT MAX(ID) FROM $wpdb->posts");
        $sqlpost2cat = "INSERT INTO $wpdb->post2cat (post_id, category_id) VALUES ('$maxid','1')";
        $sql2= "INSERT INTO $wpdb->postmeta (post_id, meta_key, meta_value) VALUES ('$maxid','_wp_page_template','livechat.php')";
        $sql3 = $wpdb->query($sql2);
        if($sql3){
            $msg .= "Guestbook Template Successfully Assigned!<br />";
            if (!$perma) {
                $msg .= "<a href=\"$home_url/?page_id=$maxid\">View Your New Live Chat!</a>";
            } else {
                $msg .= "<a href=\"$home_url/live-chat/\">View Your New Live Chat!</a>";
            }
        }else{
            $msg .= "LiveChat Template NOT Assigned!";
        }
    }
    return $msg;
}
?>